package com.tgpms.util;

import lombok.Data;

import java.math.BigInteger;
import java.nio.charset.StandardCharsets;
import java.security.MessageDigest;

/**
 * @author May
 * Created by May for 2019/4/15
 * Description: SHA加密
 */
@Data
public class Encryption {

    private String shaPassword;

    public Encryption() {

    }

    /**
     * 常规加密方式
     *
     * @param inStr
     */
    public Encryption(String inStr) {
        MessageDigest sha = null;
        try {
            sha = MessageDigest.getInstance("SHA");
        } catch (Exception e) {
            e.printStackTrace();
        }
        byte[] byteArray = inStr.getBytes(StandardCharsets.UTF_8);
        byte[] md5Bytes = sha != null ? sha.digest(byteArray) : new byte[0];
        StringBuilder hexValue = new StringBuilder();
        for (byte md5Byte : md5Bytes) {
            int val = ((int) md5Byte) & 0xff;
            if (val < 16) {
                hexValue.append("0");
            }
            hexValue.append(Integer.toHexString(val));
        }
        this.setShaPassword(hexValue.toString());
    }

    /**
     * 普通加密
     *
     * @param pwd
     * @param mode
     * @param hex
     * @return null
     */
    public String EasyEncryption(String pwd, String mode, Integer hex) {
        String result = "";
        try {
            MessageDigest messageDigest = MessageDigest.getInstance(mode);
            result = new BigInteger(1, messageDigest.digest(pwd.getBytes())).toString(hex);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return result;
    }

    /**
     * 普通加密 只根据密码
     *
     * @param pwd
     * @return null
     */
    public String EasyEncryption(String pwd) {
        String result = "";
        try {
            MessageDigest messageDigest = MessageDigest.getInstance("SHA");
            result = new BigInteger(1, messageDigest.digest(pwd.getBytes())).toString(16);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return result;
    }

    /**
     * 普通加密 密码 + 加密方式
     *
     * @param pwd
     * @param mode
     * @return null
     */
    public String EasyEncryption(String pwd, String mode) {
        String result = "";
        try {
            MessageDigest messageDigest = MessageDigest.getInstance(mode);
            result = new BigInteger(1, messageDigest.digest(pwd.getBytes())).toString(16);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return result;
    }
}
